//============================================================================
// Name        : cpp_mysql.cpp
// Author      : darkflash
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mysql/mysql.h>

#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

void mysql_client(){
	MYSQL* connection, conn;
	MYSQL_RES *sql_result;
	MYSQL_ROW sql_row;
	int query_stat;

	mysql_init(&conn);
	connection = mysql_real_connect(&conn, "127.0.0.1", "root", "", "test", 3306, (char*)NULL, 0);

	if(connection==NULL)
	{
		fprintf(stderr, "Mysql connection error : %s", mysql_error(&conn));
		return;
	}

	char *query =  "SELECT * FROM sample";
	query_stat=mysql_query(connection,query);

	if (query_stat != 0)
	{
		fprintf(stderr, "Mysql query error : %s", mysql_error(&conn));
		return;
	}

	sql_result=mysql_store_result(connection);
	while((sql_row=mysql_fetch_row(sql_result))!=NULL)
	{
		printf("%s %s %s\n",sql_row[0],sql_row[1],sql_row[2]);
	}
	mysql_free_result(sql_result);

	mysql_close(connection);
}

void mysql_connector()
{
	try{
		sql::Driver* driver;
		sql::Connection* conn;
		sql::Statement* stmt;
		sql::ResultSet* res;

		/* Create a connection */
		driver = get_driver_instance();
		conn = driver->connect("tcp://127.0.0.1:3306", "root", "");

		/* Connect to the MySQL test database */
		conn->setSchema("test");

		stmt = conn->createStatement();

		res = stmt->executeQuery("SELECT * FROM sample");

		while (res->next()) {
			cout << res->getString("ID") << endl;
			/* Access column fata by numeric offset, 1 is the first column */
			cout << res->getString(1) << endl;
		}
		delete res;
		delete stmt;
		delete conn;
	}catch(sql::SQLException &ex){
		cout << "# ERR: " << ex.what();
		cout << " (MySQL error code: " << ex.getErrorCode();
	}
}

int main() {
	mysql_client();
	mysql_connector();

	return 0;
}
